/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.concurrent;

import java.util.Random;
import java.util.concurrent.Semaphore;

class UserThrad extends Thread {
    private String name;
    private Semaphore jsShop;

    public UserThrad(String name, Semaphore jsShop) {
        this.name = name;
        this.jsShop = jsShop;
    }

    @Override
    public void run() {
        // 剩下的技师
        int availablePermits = jsShop.availablePermits();
        if (availablePermits > 0) {
            System.out.println(name + ",找到小姐姐按摩了....");
        } else {
            System.out.println(name + ",真可惜，还得等...");
        }
        try {
            // 申请技师
            jsShop.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "开始按摩咯" + ",剩下的技师数:" + jsShop.availablePermits());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (Exception e) {

        }
        System.out.println(name + "按摩完咯!，舒服");
        // 释放技师
        jsShop.release();
    }
}

public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        for (int i = 1; i <= 10; i++) {
            UserThrad userThrad = new UserThrad("第" + i + "个人", semaphore);
            userThrad.start();
        }
    }

}